<template>
  <view class="test-container">
    <view class="title">直接测试后端连接</view>
    <button @click="testDirectRequest" class="test-btn">使用uni.request</button>
    <button @click="testWithFetch" class="test-btn">使用fetch API</button>
    <button @click="testNetworkStatus" class="test-btn">测试网络状态</button>
    <view class="log-container">
      <text class="log-title">请求结果:</text>
      <text class="log-content">{{ result }}</text>
    </view>
    <view class="log-container">
      <text class="log-title">网络信息:</text>
      <text class="log-content">{{ networkInfo }}</text>
    </view>
  </view>
</template>

<script>

export default {
  data() {
    return {
      result: '',
      networkInfo: ''
    }
  },
  methods: {
    testDirectRequest() {
      this.result = '正在发送请求...'
      
      // 直接使用uni.request发送请求，绕过request.js封装
      console.log('===== 测试uni.request请求 =====');
      console.log('请求URL: http://localhost:8080/auth/sendCode/19852725830');
      console.log('withCredentials设置为true');
      
      uni.request({
        url: '/api/auth/sendCode/19852725830',
        method: 'GET',
        header: {
          'isToken': 'false',
          'Content-Type': 'application/json'
        },
        timeout: 20000,
        withCredentials: true, // 添加withCredentials配置
        success: (res) => {
          console.log('直接请求成功:', res)
          this.result = '请求成功!\n' + JSON.stringify(res.data, null, 2)
        },
        fail: (err) => {
          console.error('直接请求失败:', err)
          this.result = '请求失败!\n' + JSON.stringify(err, null, 2)
          // 记录详细错误信息
          console.log('错误码:', err.errCode || '未知')
          console.log('错误信息:', err.errMsg || '未知')
        },
        complete: () => {
          console.log('请求完成')
        }
      })
    },
    
    // 使用浏览器原生的fetch API测试
    testWithFetch() {
      this.result = '正在使用fetch API发送请求...'
      
      console.log('===== 测试fetch API请求 =====');
      console.log('请求URL: http://localhost:8080/auth/sendCode/19852725830');
      
      // 使用全局的fetch对象（在浏览器环境中可用）
      if (typeof window !== 'undefined' && window.fetch) {
        const startTime = Date.now();
        
        fetch('/api/auth/sendCode/19852725830', {
          method: 'GET',
          headers: {
            'isToken': 'false',
            'Content-Type': 'application/json'
          },
          credentials: 'include', // 相当于withCredentials: true
          timeout: 20000
        })
        .then(response => {
          const endTime = Date.now();
          console.log('fetch响应状态码:', response.status);
          console.log('fetch响应头:', Array.from(response.headers.entries()));
          console.log('fetch响应时间:', endTime - startTime, 'ms');
          
          if (!response.ok) {
            throw new Error(`HTTP错误! 状态码: ${response.status}`);
          }
          return response.json();
        })
        .then(data => {
          console.log('fetch请求成功:', data);
          this.result = 'fetch请求成功!\n' + JSON.stringify(data, null, 2);
        })
        .catch(error => {
          const endTime = Date.now();
          console.error('fetch请求失败:', error);
          this.result = 'fetch请求失败!\n' + error.message + '\n详细信息请查看控制台';
        });
      } else {
        this.result = '当前环境不支持fetch API';
        console.log('当前环境不支持fetch API');
      }
    },
    
    // 测试网络状态
    testNetworkStatus() {
      this.networkInfo = '正在获取网络信息...';
      
      // 获取网络状态
      uni.getNetworkType({
        success: (res) => {
          console.log('网络类型:', res.networkType);
          this.networkInfo += '\n网络类型: ' + res.networkType;
        },
        fail: (err) => {
          console.error('获取网络类型失败:', err);
          this.networkInfo += '\n获取网络类型失败: ' + err.errMsg;
        }
      });
      
      // 测试本地IP连接
      if (typeof window !== 'undefined' && window.XMLHttpRequest) {
        const xhr = new XMLHttpRequest();
        xhr.open('GET', 'http://localhost:8080', true);
        xhr.timeout = 5000;
        
        xhr.onload = () => {
          console.log('XMLHttpRequest连接成功，状态码:', xhr.status);
          this.networkInfo += '\nXMLHttpRequest连接成功，状态码: ' + xhr.status;
        };
        
        xhr.onerror = () => {
          console.error('XMLHttpRequest连接失败');
          this.networkInfo += '\nXMLHttpRequest连接失败';
        };
        
        xhr.ontimeout = () => {
          console.error('XMLHttpRequest连接超时');
          this.networkInfo += '\nXMLHttpRequest连接超时';
        };
        
        xhr.send();
      }
      
      // 显示浏览器信息
      if (typeof navigator !== 'undefined') {
        console.log('浏览器信息:', navigator.userAgent);
        this.networkInfo += '\n浏览器: ' + navigator.userAgent.substring(0, 100) + '...';
      }
    }
  },
  
  // 页面加载时自动测试网络状态
  onLoad() {
    this.testNetworkStatus();
  }
}
</script>

<style scoped>
.test-container {
  padding: 20rpx;
}
.title {
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 30rpx;
  text-align: center;
}
.test-btn {
  background-color: #007aff;
  color: white;
  margin: 20rpx 0;
}
.log-container {
  margin-top: 20rpx;
  border: 1rpx solid #eee;
  padding: 10rpx;
  min-height: 300rpx;
}
.log-title {
  font-weight: bold;
  display: block;
  margin-bottom: 10rpx;
}
.log-content {
  font-size: 28rpx;
  white-space: pre-wrap;
}
</style>